package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.*;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
       private UserRoleMapper userRoleMapper;
    //设备维护人员的角色名称
    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    //超级管理员的角色名称
    @Value("${zzyl.alert.managerRole}")
    private String managerRole;
    /**
     * 新增报警规则
     *
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }
    //校验设备上报数据，进行报警规则过滤处理
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
    //获取上报数据如果为1分钟前就不再处理为历史数据
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between>60){
            return;
        }
        //查询报警规则，将全部设备的报警规则和本地报警规则合并
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        List<AlertRule> alertRules1 = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(),deviceDataVo.getProductKey());
        Collection<AlertRule>alertRules3=CollUtil.addAll(alertRules,alertRules1);
        //如果报警规则为空，程序结束
        if (CollectionUtil.isEmpty(alertRules3)){
            return;
        }
        //报警规则不为空就遍历报警规则进行校验
        alertRules3.forEach(alertRule -> deviceDateAlarmHandler(deviceDataVo,alertRule));

    }

    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //第一层校验：判断是否在生效时间段内
        String[] aepArr = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(aepArr[0]);
        LocalTime endTime = LocalTime.parse(aepArr[1]);
        //上报时间
     LocalTime time = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();
        //如果上报时间不在生效时间段内，校验结束
        if (startTime.isAfter(time) || endTime.isBefore(time)){
            return;
        }
        //设备Id
        String iotId = deviceDataVo.getIotId();
        //从redis中获取数据，报警规则连续触发次数rediskey
   String aggCounKey=CacheConstants.ALERT_SILENT_PREFIX+iotId+":"+deviceDataVo.getFunctionId()+":"+ alertRule.getId();

        //第二层校验：将设备上报值和阈值比较
        //x – 第一个值，y – 第二个值。x==y返回0，x<y返回小于0的数，x>y返回大于0的数
        int compareResult = NumberUtil.compare(Double.parseDouble(deviceDataVo.getDataValue()), alertRule.getValue());
        //或 逻辑运算，2个条件满足其一即为true
        //1、运算符为>=,且设备报错>=阈值
        //2、运算符为<,且设备报错<阈值
   if ((ObjectUtil.equals(alertRule.getOperator(),">=")&& compareResult>=0)||(ObjectUtil.equals(alertRule.getOperator(),"<")&& compareResult<0)){
       log.debug("此时设备上报数据达到峰值");
   }else {
       //该情况不符合报警规则，所以设备上报数据为正常数据，需要删除redis聚合的异常数据，程序结束
       redisTemplate.delete(aggCounKey);
       return;
   }
        //第三层校验：校验当前设备+功能的报警规则是否处于沉默周期
        String silentCachekey =CacheConstants.ALERT_SILENT_PREFIX+iotId+":"+deviceDataVo.getFunctionId()+":"+alertRule.getId();
   String silenData=redisTemplate.opsForValue().get(silentCachekey);
        //如果redis中存在对应沉默周期数据，则当前设备+功能正处在沉默周期，无需报警
        if (StringUtils.isNotEmpty(silenData)){
            return;
        }
        //第四层校验：校验持续周期
        //4.1获取连续触发报警规则的次数
        //aggCountData是上次触发报警累计到的次数，这一次又触发了报警，所以累计到这次就+1
        String aggCountData = redisTemplate.opsForValue().get(aggCounKey);
        int triggerCount=ObjectUtil.isEmpty(aggCountData)?1:Integer.parseInt(aggCountData)+1;
        //4.2判断次数是否与持续周期相等
        //如果触发报警规则次数不等于持续周期，则无需报警
        if (com.zzyl.utils.ObjectUtil.notEqual(alertRule.getDuration(),triggerCount)){
            redisTemplate.opsForValue().set(aggCounKey,triggerCount+"");
            return;
        }
        //如果触发报警规则次数等于持续周期，则需要报警，完成以下操作
        //1）删除报警规则连续触发次数的缓存
        //2）添加对应的沉默周期，设置过期时间添加对应的沉默周期，设置过期时间
        //3）报警数据存储到数据库
        redisTemplate.delete(aggCounKey);
        redisTemplate.opsForValue().set(silentCachekey,deviceDataVo.getDataValue(),alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //获取消息的消费者
        List<Long> consumerIds=null;
        if (ObjectUtil.equals(0,alertRule.getAlertDataType())){
 //如果老人报警数据，需要通知绑定老人的护理员，根据iotId查询老人绑定的护理员
            if (deviceDataVo.getLocationType()==0){
               consumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if (deviceDataVo.getLocationType()==1&&deviceDataVo.getPhysicalLocationType()==2){
               consumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }else {
                consumerIds=userRoleMapper.selectUserIdsByRoleName(deviceMaintainerRole);
            }
            //查询超级管理员，超级管理员无论什么消息都会接收
            List<Long> managerIds = userRoleMapper.selectUserIdsByRoleName(managerRole);
            List<Long> allConsumerIds = CollUtil.addAllIfNotContains(consumerIds, managerIds);
                allConsumerIds = CollUtil.distinct(allConsumerIds);
            //新增报警设备数据
            insertAlerData(deviceDataVo,alertRule, allConsumerIds);
        }

    }
    @Autowired
    private AlertDataMapper alertDataMapper;
//新增报警数据
    private void insertAlerData(DeviceDataVo deviceDataVo, AlertRule alertRule, List<Long> allConsumerIds) {
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = allConsumerIds.stream().map(id -> {

            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;

        }).collect(Collectors.toList());
   alertDataMapper.batchInsert(list);
    }


}
